﻿using Elasticsearch.Net;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BuddHa.ES
{
    public class ElasticSearchClient
    {
        private ElasticClient _elasticClient;
        private List<Uri> _listNode = new List<Uri>();
        private string _index = String.Empty;

        public ElasticSearchClient(string[] nodeStr, string index)
        { 
            _index = index;
            foreach (var node in nodeStr)
            {
                _listNode.Add(new Uri(node));
            }
        }

        public void Initialization()
        {
            if (_listNode != null)
            {
                var pool = new StaticConnectionPool(_listNode);
                var settings = new ConnectionSettings(pool);
                settings.DisableDirectStreaming(true);
                _elasticClient = new ElasticClient(settings);
            }
        }

        public async Task<Tuple<ISearchResponse<SourceData>, long>> GetSourceDatas(DateTime? startTime, DateTime? endTime, string uri, string requestBody, string responseBody, string quartzName, int minMilliSeconds = 0, int maxMilliSeconds = 500000, int index = 0, int size = 100)
        {

            Initialization();
            var esIndexName = Indices.Index(_index);
            var response = await _elasticClient.SearchAsync<SourceData>(s => s
            .Index(esIndexName)
            .From(index)
            .Size(size)
            .Query(q => q.Match(m => m.Field(f => f.Uri).Query(uri)) &&
                        q.Match(m => m.Field(f => f.RequestBody).Query(requestBody)) &&
                        q.Match(m => m.Field(f => f.ResponseBody).Query(responseBody)) &&
                        q.Match(m => m.Field(f => f.QuartzName).Query(quartzName)) &&
                        //q.TermRange(t => t.GreaterThan(minMilliSeconds.ToString()).LessThan(maxMilliSeconds.ToString()).Field(f => f.ElapsedMilliseconds)) &&
                        q.DateRange(d => d.Field(f => f.TimeStamp)
                                              .GreaterThanOrEquals(startTime)
                                              .LessThanOrEquals(endTime))));
            return new Tuple<ISearchResponse<SourceData>, long>(response, response.Total);
        }
    }
}
